import { ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges, TemplateRef } from '@angular/core';
import { ApesNoAnimationDirective, FunctionProp, valueFunctionProp } from '@shared/apes/core';

import { AbstractPickerComponent } from './abstract-picker.component';
import { CandyDate } from './lib/candy-date/candy-date';
import { PanelMode } from './standard-types';
import { ApesI18nService, DateHelperService } from '@shared/apes/i18n';

/**
 * The base picker for header panels, current support: Year/Month
 */

@Component({
  template: ``
})
export class HeaderPickerComponent extends AbstractPickerComponent implements OnInit, OnChanges {
  @Input() apesPlaceHolder: string;

  @Input() apesRenderExtraFooter: FunctionProp<TemplateRef<void> | string>;
  @Input() apesDefaultValue: CandyDate;
  @Input() apesFormat: string; // [Canmplemented by sub class] The output format
  endPanelMode: SupportHeaderPanel; // [Implemented by sub class] The final panel for picking a date
  panelMode: PanelMode; // Current panel mode
  extraFooter: TemplateRef<void> | string;

  private supportPanels: PanelMode[];

  constructor(i18n: ApesI18nService,
              cdr: ChangeDetectorRef,
              dateHelper: DateHelperService,
              noAnimation?: ApesNoAnimationDirective) {
    super(i18n,cdr,dateHelper,noAnimation);
  }

  ngOnInit(): void {
    super.ngOnInit();

    this.panelMode = this.endPanelMode;

    const allHeaderPanels: PanelMode[] = [ 'decade', 'year', 'month' ];
    this.supportPanels = allHeaderPanels.slice(0, allHeaderPanels.indexOf(this.endPanelMode) + 1);
  }

  ngOnChanges(changes: SimpleChanges): void {
    super.ngOnChanges(changes);

    if (changes.apesRenderExtraFooter) {
      this.extraFooter = valueFunctionProp(this.apesRenderExtraFooter);
    }
  }

  onPanelModeChange(mode: PanelMode): void {
    if (this.supportPanels.indexOf(mode) > -1) {
      this.panelMode = mode;
    } else { // Since the default "click year" logic can be "year panel" -> "date panel", we need force to the end panel otherwise
      this.panelMode = this.endPanelMode;
    }
  }

  onChooseValue(mode: SupportHeaderPanel, value: CandyDate): void {
    if (this.endPanelMode === mode) {
      super.onValueChange(value);

      this.closeOverlay();
    }
  }

  onOpenChange(open: boolean): void {
    if (!open) {
      this.cleanUp();
    }
    this.apesOnOpenChange.emit(open);
  }

  // Restore some initial props to let open as new in next time
  private cleanUp(): void {
    this.panelMode = this.endPanelMode;
  }
}

export type SupportHeaderPanel = 'year' | 'month';
